﻿using Max.Ph5_2009A.NewShopping.Domain;
using Max.Ph5_2009A.NewShopping.DTO;
using Max.Ph5_2009A.NewShopping.IRespository;
using Max.Ph5_2009A.NewShopping.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.Ph5_2009A.NewShopping.Service
{
    public class OrderMasterInfoService : BaseService<OrderMasterInfoModel>, IOrderMasterInfoService
    {
        IOrderMasterInfoRespository _respository;
        IOrderDetailInfoRespository _detailInfoRespository;
        IProductSKURespository _skuRespository;
        IUnitOfWork _unitOfWork;
        public OrderMasterInfoService(IOrderMasterInfoRespository respository,
            IOrderDetailInfoRespository detailInfoRespository,
            IProductSKURespository skuRespository, IUnitOfWork unitOfWork) : base(respository, unitOfWork)
        {
            _respository = respository;
            _detailInfoRespository = detailInfoRespository;
            _skuRespository = skuRespository;
            _unitOfWork = unitOfWork;
        }

        public string CreateOrder(CreateOrderInputDto dto)
        {
            /*
             * 创建订单，需要做三件事
             * 1、创建订单
             * 2、处理库存
             * 3、修改购物车
             * 
             * **/

            using (var _tran = _unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //1、生成订单

                    //订单数据
                    var order = new Domain.OrderMasterInfoModel()
                    {
                        MemberId = dto.OrderMaster.MemberId,
                        OrderNo = BuilderOrderNo(),
                        DiscountMoney = dto.OrderMaster.DiscountMoney,
                        PayMoney = dto.OrderMaster.PayMoney,
                        RecivedAddress = dto.OrderMaster.RecivedAddress,
                        RecivedName = dto.OrderMaster.RecivedName,
                        RecivedPhone = dto.OrderMaster.RecivedPhone,
                        Total = dto.OrderMaster.Total
                    };
                    _respository.Insert(order);

                    //订单明细--即商品列表数据  

                    var detialData = new List<Domain.OrderDetailInfoModel>();
                    dto.OrderDetails.ForEach(x =>
                    {
                        detialData.Add(new OrderDetailInfoModel
                        {
                            GoodsId = x.GoodsId,
                            GoodsNumber = x.GoodsNumber,
                            GoodsPrice = x.GoodsPrice,
                            OrderNo = order.OrderNo //订单号，是主表的订单号

                        });
                    });

                    detialData.ForEach(x =>
                    {
                        _detailInfoRespository.Insert(x);
                    });

                    //2、处理库存(处理订单明细中的商品的库存)
                    //锁定库存 += 购买的数量
                    //可用库存 -= 购买的数量
                    detialData.ForEach(d =>
                    {
                        //var m =  _context.ProductSKUs.Where(x => x.Id == d.GoodsId).FirstOrDefault();
                        var m = _skuRespository.Select().Where(x => x.Id == d.GoodsId).FirstOrDefault();
                        if (m != null)
                        {
                            m.LockStock += d.GoodsNumber;
                            m.VaildStock -= d.GoodsNumber;

                            //修改了库存记得更新到数据库
                            _skuRespository.Update(m);
                        }
                    });

                    //3、处理购物车（从购物车中，删除已购买的商品）
                    var key = order.MemberId.ToString().ToUpper();
                    var _redis = new CSRedis.CSRedisClient("127.0.0.1:6379");
                    var _carList = _redis.Get<List<ShoppingCarDto>>(key);
                    if (_carList != null)
                    {
                        detialData.ForEach(d =>
                        {
                            var m = _carList.Where(x => x.GoodsId.Equals(d.GoodsId.ToString())).FirstOrDefault();
                            if (m != null)
                            {
                                _carList.Remove(m);
                            }
                        });
                        _redis.Set(key, _carList);  //删除了之后，记得更新到redis缓存
                    }
                    _unitOfWork.SaveChanges();
                    _tran.Commit();

                    //返回订单号
                    return order.OrderNo;
                }
                catch (Exception)
                {
                    _tran.Rollback();
                    return "-1";
                }
            }
        }

        //支付成功
        public void PaySuccess(string orderNo)
        {
            //支付成功，要做二件事
            //1、修订订单状态
            //2、修改库存

            using (var tran = _unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    var o = _respository.Select().Where(x => x.OrderNo.Equals(orderNo)).FirstOrDefault();
                    if (o != null)
                    {
                        o.OrderState = Domain.Shared.OrderState.ToBeShipped;
                        _respository.Update(o);

                        //找到这个订单的商品
                        var detail = _detailInfoRespository.Select().Where(prop => prop.OrderNo.Equals(orderNo));
                        if (detail != null && detail.Count() > 0)
                        {
                            //处理具体的某一个商品
                            detail.ToList().ForEach(x =>
                            {
                            //在库存SKU表中，找到具体的某个商品
                            var single = _skuRespository.Select().Where(p => p.Id == x.GoodsId).FirstOrDefault();
                                if (single != null)
                                {
                                    single.LockStock -= x.GoodsNumber;
                                    _skuRespository.Update(single);
                                }
                            });
                        }
                    }
                    _unitOfWork.SaveChanges();
                    tran.Commit();
                }
                catch (Exception)
                {
                    tran.Rollback();
                }
            }
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <returns></returns>
        private string BuilderOrderNo(string t = "P")
        {
            //以往订单号：雪花ID，GUID
            //现在订单号：是有业务体现
            //格式：客户端(P/M) + 日期 + 流水号
            // M202304088569
            string date = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string number = new Random().Next(0, 9999).ToString().PadLeft(4);  //生成是1，订单号：P202304080001

            return $"{t}{date}{number}";
        }
    }
}
